package org.opens.lambda.parallel;

import java.util.concurrent.RecursiveTask;

/**
 * 简介:
 *      RecursiveTask<T>是Fork join框架的一个类, 用来执行并行处理, T为返回值类型.
 */
public class AccmulatorRecursiveTask extends RecursiveTask<Integer> {

    private final int start;

    private final int end;

    private final int[] data;

    private final int LIMIT = 3;

    public AccmulatorRecursiveTask(int start, int end, int[] data) {
        this.start = start;
        this.end = end;
        this.data = data;
    }

    @Override
    protected Integer compute() {
        if((end - start) <= LIMIT) {
            int result = 0;
            for(int i = start; i < end; i++) {
                result += data[i];
            }
            return result;
        }

        int middle = ( start + end ) / 2;
        AccmulatorRecursiveTask left = new AccmulatorRecursiveTask(start, middle, data);
        AccmulatorRecursiveTask right = new AccmulatorRecursiveTask(middle, end, data);
        left.fork();
        Integer rightResult = right.compute();
        Integer leftResult = left.join();
        return rightResult + leftResult;
    }
}
